package org.grow.util.service.impl;

import org.grow.util.service.CodeGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

/**
 * @Author: xwg
 * @CreateDate: 2025/10/10
 */

@Service
public class RedisCodeGenerator implements CodeGenerator {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public String nextCode(String prefix) {
        String head = prefix;
        String body = "";
        String foot = "";

        body = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
//        System.out.println(body);

        String p = "MYCODE:";
        String key = p+prefix;
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
//      setnx() 懒加载思维
        ops.setIfAbsent(key, String.valueOf(10));
        String s = ops.get(key);
        //      生成器思维 为了可能存在的下一次需求 提前准备
        ops.increment(key);
        foot = String.format("%06d",Integer.parseInt(s));

        return head+body+foot;
    }
}
